package cn.school.demo.repository

import android.graphics.Color
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.school.demo.MyApplication
import cn.school.demo.pojo.*
import cn.school.demo.util.HttpApi
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.reflect.TypeToken
import com.mylhyl.circledialog.CircleDialog
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

const val BASEURL = "http://120.53.123.145:8888/"

class AnswerRepository {
    private val httpApi: HttpApi

    init {
        val retrofit =
            Retrofit.Builder().baseUrl(DataRepository.BASEURL).addConverterFactory(
                GsonConverterFactory.create()
            )
                .build()
        httpApi = retrofit.create(HttpApi::class.java)
    }

    fun getPartyHistoryAnswer(
        id: Int,
        title: String,
        topicName: String?,
        f: FragmentManager
    ): LiveData<MutableList<Test>> {
        val responseLiveData = MutableLiveData<MutableList<Test>>()
        val params = topicName?.let {
            mapOf<String, Any>(
                "sfNumber" to id,
                "subjectTitle" to title,
                "topicName" to topicName
            )
        } ?: mapOf<String, Any>(
            "sfNumber" to id,
            "subjectTitle" to title
        )
        httpApi.getPartyHistoryAnswer(params).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    when (it.success) {
                        true -> {
                            LogUtils.d("${title}获取TestList成功！")
                            try {
                                responseLiveData.value = GsonUtils.fromJson<MutableList<Test>>(
                                    it.data["test"].toString(),
                                    object : TypeToken<MutableList<Test>>() {}.type
                                )
                            } catch (e: Error) {
                                e.printStackTrace()
                            }
                        }
                        else -> {
                            CircleDialog.Builder().setTextColor(Color.RED).setText(it.message)
                                .setNegative("确认", null).show(f)
                            LogUtils.e(it.message)
                            //ToastUtils.showShort(it.message)
                        }
                    }
                } ?: LogUtils.e("党史答题http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }

        })
        return responseLiveData
    }

    fun getProfessionalList(): LiveData<MutableList<String>> {
        val responseLiveData = MutableLiveData<MutableList<String>>()
        httpApi.getProfessionalList().enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    try {
                        responseLiveData.value = GsonUtils.fromJson<MutableList<String>>(
                            response.body()!!.data["specialName"].toString(),
                            object : TypeToken<MutableList<String>>() {}.type
                        )
                    } catch (e: Error) {
                        e.printStackTrace()
                    }
                } ?: LogUtils.e("专项答题http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData

    }

    fun saveAnswerIntegral(params: Map<String, Any>): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        httpApi.saveAnswerIntegral(params).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    responseLiveData.value = it
                } ?: LogUtils.e("保存答题记录积分http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }

    fun getSubjectListById(id: Int, signId: Int): LiveData<MutableList<Subject>> {
        val responseLiveData = MutableLiveData<MutableList<Subject>>()
        MyApplication.isNoFresh = true
        httpApi.getSubjectListById(mapOf("signId" to id, "sfNumber" to signId))
            .enqueue(object : Callback<Result> {
                override fun onResponse(call: Call<Result>, response: Response<Result>) {
                    response.body()?.let {
                        if (it.success) {
                            try {
                                val map = GsonUtils.fromJson<MutableList<Subject>>(
                                    it.data["subject"].toString(),
                                    object : TypeToken<MutableList<Subject>>() {}.type
                                )
                                LogUtils.d(map.toString())
                                responseLiveData.value = map
                            } catch (e: Error) {
                                e.printStackTrace()
                            }
                        } else {
                            LogUtils.e(it.message)
                            responseLiveData.value = mutableListOf()
                        }
                        MyApplication.isNoFresh = false
                    } ?: LogUtils.e("获取答题http返回值为空！")
                }

                override fun onFailure(call: Call<Result>, t: Throwable) {
                    LogUtils.e(t)
                }

            })
        return responseLiveData
    }

    fun saveAnswer(answer: Answer): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        httpApi.saveAnswer(mapOf("answer" to GsonUtils.toJson(answer)))
            .enqueue(object : Callback<Result> {
                override fun onResponse(call: Call<Result>, response: Response<Result>) {
                    response.body()?.let {
                        responseLiveData.value = it
                    } ?: LogUtils.e("保存答题记录http返回值为空！")
                }

                override fun onFailure(call: Call<Result>, t: Throwable) {
                    LogUtils.e(t)
                }

            })
        return responseLiveData
    }

    fun getSubjectListByTrueTime(): LiveData<MutableList<Subject>> {
        val responseLiveData = MutableLiveData<MutableList<Subject>>()
        httpApi.getSubjectListByTrueTime().enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    LogUtils.d(it.toString())
                    try {
                        val map = GsonUtils.fromJson<MutableList<Subject>>(
                            it.data["subject"].toString(),
                            object : TypeToken<MutableList<Subject>>() {}.type
                        )
                        LogUtils.d(map)
                        if (map != null) {
                            responseLiveData.value = map
                        } else {
                            responseLiveData.value = mutableListOf()
                        }
                    } catch (e: Error) {
                        e.printStackTrace()
                    }
                } ?: LogUtils.e("获取可答试卷http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }
}